package com.wocai.jrt.orgadmin.project.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.approve.model.ApproveRoleGroup;
import com.wocai.jrt.orgadmin.approve.model.ApproveRoleGroupMember;
import com.wocai.jrt.orgadmin.approve.service.spi.ApproveRoleGroupMemberService;
import com.wocai.jrt.orgadmin.approve.service.spi.ApproveRoleGroupService;
import com.wocai.jrt.orgadmin.asset.model.AssetAllocationDetail;
import com.wocai.jrt.orgadmin.asset.service.spi.AssetAllocationDetailService;
import com.wocai.jrt.orgadmin.enterprise.model.Enterprise;
import com.wocai.jrt.orgadmin.enterprise.model.EnterpriseWithBLOBs;
import com.wocai.jrt.orgadmin.enterprise.service.spi.EnterpriseService;
import com.wocai.jrt.orgadmin.flow.model.Flow;
import com.wocai.jrt.orgadmin.flow.model.FlowLog;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowLogService;
import com.wocai.jrt.orgadmin.project.bean.ApproveGroupType;
import com.wocai.jrt.orgadmin.project.bean.OperaterUtils;
import com.wocai.jrt.orgadmin.project.bean.ProjectReqBean;
import com.wocai.jrt.orgadmin.project.bean.ProjectResBean;
import com.wocai.jrt.orgadmin.project.bean.ProjectStateUtils;
import com.wocai.jrt.orgadmin.project.model.Project;
import com.wocai.jrt.orgadmin.project.model.ProjectAttachment;
import com.wocai.jrt.orgadmin.project.model.ProjectGrade;
import com.wocai.jrt.orgadmin.project.service.spi.ProjectAttachmentService;
import com.wocai.jrt.orgadmin.project.service.spi.ProjectGradeService;
import com.wocai.jrt.orgadmin.project.service.spi.ProjectService;
import com.wocai.jrt.orgadmin.utils.ImgType;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 项目控制器
 * 
 * @author yinlei
 * @date 2016-3-17 17:23:18
 */
@Controller
@RequestMapping("/project")
public class ProjectAction extends GenericAction<Project> {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(ProjectAction.class);
	
	private static final Pattern IMAGE = Pattern
			.compile("^[\u4e00-\u9fffa-zA-Z0-9_\\(\\)\\-\\s.]+.(jpg|jpeg|gif|png|bmp)$");

	@Inject
	private ProjectService projectServiceImpl;
	@Inject
	private EnterpriseService enterpriseServiceImpl;
	@Inject
	private ApproveRoleGroupMemberService approveRoleGroupMemberServiceImpl;
	@Inject
	private ApproveRoleGroupService approveRoleGroupServiceImpl;
	@Inject
	private ProjectAttachmentService projectAttachmentServiceImpl;
	@Inject
	private ProjectGradeService projectGradeServiceImpl;
	@Inject
	private FlowLogService flowLogServiceImpl;
	@Inject
	private AssetAllocationDetailService assetAllocationDetailServiceImpl;
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}
	
	/**
	 * 根据Id获得项目实体，Json格式。
	 * 
	 * @param id
	 *            参数id
	 * @return 项目实体
	 */
	@ResponseBody
	@RequestMapping("/get")
	public Project get(String id) {
		Project model = null;
		try {
			model = projectServiceImpl.get(id);
		} catch (Exception e) {
			LOGGER.error("get record error, errorMsg=[{}].", e.getMessage());
		}
		return model;
	}

	/**
	 * 跳转到新增页面
	 * 
	 * @return 新增页面逻辑视图
	 */
	@RequestMapping("/add")
	public String add(Map<String, Object> maps) {
		EnterpriseWithBLOBs e = new EnterpriseWithBLOBs();
		String orgId = UserUtils.getOrgId();
		e.setOrgId(orgId);
		List<Enterprise> eList = enterpriseServiceImpl.queryList(e);
		ApproveRoleGroup ag = new ApproveRoleGroup();
		ag.setOrgId(orgId);
		ag.setType(5);

		ag = approveRoleGroupServiceImpl.unique(ag);
		if (null == ag) {
			if (LOGGER.isInfoEnabled()) {
				LOGGER.info("法律合规部门未设置");
			}
			maps.put("approveRoleGroupMemberList", ListUtils.EMPTY_LIST);
		} else {
			ApproveRoleGroupMember approve = new ApproveRoleGroupMember();
			approve.setId(ag.getId());
			List<ApproveRoleGroupMember> aMembers = approveRoleGroupMemberServiceImpl
					.getApproveGroupEmpList(approve);
			maps.put("approveRoleGroupMemberList", aMembers);
		}

		maps.put("enterpriseList", eList);

		return "project/add";
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(
			HttpServletRequest request,
			@Valid ProjectReqBean model,
			@RequestParam(value = "fileList", required = false) List<MultipartFile> fileList,
			BindingResult errors) {
		JsonBean bean = new JsonBean();
		try {
			if (StringUtils.isBlank(model.getType().toString())) {
				bean.setCode(0);
				bean.setMessage("类型不能为空");
				LOGGER.error("类型不能为空");
				return bean;
			}
			if (2 == model.getType()) {
				model.setGuaranteeType(null);
				model.setGuaranteeEnterpriseId(null);
				model.setGuaranteeAssess(null);
				if (LOGGER.isInfoEnabled()) {
					LOGGER.info("类型为股权类 三个参数设为null");
				}
			} else {
				if (StringUtils.isBlank(model.getGuaranteeType().toString())) {
					bean.setCode(0);
					bean.setMessage("当前类型下担保方式不能为空");
					LOGGER.error("当前类型下担保方式不能为空");
					return bean;
				}
				Integer guarantee = model.getGuaranteeType();
				if (1 == guarantee) {
					if (StringUtils.isBlank(model.getGuaranteeEnterpriseId())) {
						bean.setCode(0);
						bean.setMessage("参数不齐");
						LOGGER.error("类型参数不齐");
						return bean;
					}
					model.setGuaranteeAssess(null);
					if (LOGGER.isInfoEnabled()) {
						LOGGER.info("保证 抵押物状况设为null");
					}
				} else {
					if (StringUtils.isAnyBlank(
							model.getGuaranteeEnterpriseId(),
							model.getGuaranteeAssess())) {
						bean.setCode(0);
						bean.setMessage("参数不齐");
						LOGGER.error("类型参数不齐");
						return bean;
					}
				}
			}
			if (StringUtils.isAnyBlank(model.getAmount().toString(),
					model.getCode(), model.getEnterpriseId(),
					model.getIntroduction(), model.getLawEmployeeId(),
					model.getName())) {
				bean.setCode(0);
				bean.setMessage("参数不齐");
				LOGGER.error("基础参数不齐");
				return bean;
			}
			bean = projectServiceImpl.saveProject(model, fileList);
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 查看项目详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 项目详情页
	 */
	@RequestMapping("/detail/{id}")
	public String detail(@PathVariable("id") String id,Map<String, Object> maps) {
		try {
			if(StringUtils.isBlank(id)){
				return "common/error";
			}
			//判断当前项目是否入库
			Project model = projectServiceImpl.get(id);
			boolean flag = false;
			if(model.getState() == 10 || model.getState() == 11 || model.getState() == 12){
				flag = true;
			}
			//获取机构尽调小组信息
			ApproveRoleGroup arg = new ApproveRoleGroup();
			arg.setOrgId(UserUtils.getOrgId());
			arg.setType(2);
			arg.setProjectId(id);
			List<ApproveRoleGroup> argList = approveRoleGroupServiceImpl.pagedList(arg);
			EnterpriseWithBLOBs e = new EnterpriseWithBLOBs();
			String orgId = UserUtils.getOrgId();
			e.setOrgId(orgId);
			List<Enterprise> eList = enterpriseServiceImpl.queryList(e);
			//获取法律合规部
			ApproveRoleGroup ag = new ApproveRoleGroup();
			ag.setOrgId(orgId);
			ag.setType(5);

			ag = approveRoleGroupServiceImpl.unique(ag);
			if (null == ag) {
				if (LOGGER.isInfoEnabled()) {
					LOGGER.info("法律合规部门未设置");
				}
				maps.put("approveRoleGroupMemberList", ListUtils.EMPTY_LIST);
			} else {
				ApproveRoleGroupMember approve = new ApproveRoleGroupMember();
				approve.setId(ag.getId());
				List<ApproveRoleGroupMember> aMembers = approveRoleGroupMemberServiceImpl
						.getApproveGroupEmpList(approve);
				maps.put("approveRoleGroupMemberList", aMembers);
			}

			maps.put("enterpriseList", eList);
			LOGGER.info("edit project detail param id: [{}]",JSON.toJSONString(id));
			ProjectAttachment pAttachment = new ProjectAttachment();
			pAttachment.setProjectId(id);
			pAttachment.setType(1);
			List<ProjectAttachment> paList = projectAttachmentServiceImpl.queryList(pAttachment);
			ProjectAttachment prAttachment = new ProjectAttachment();
			prAttachment.setProjectId(id);
			prAttachment.setType(2);
			List<ProjectAttachment> paReportList = projectAttachmentServiceImpl.queryList(prAttachment);
			maps.put("project", model);
			maps.put("flag", flag);
			if(argList.size() > 0){
				maps.put("report", argList.get(0));	
			}
			maps.put("projectAttachmentList", paList);
			maps.put("projectReportAttachmentList", paReportList);
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "project/detail";
	}

	/**
	 * 跳转到编辑信息页面
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 编辑页面
	 */
	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, Map<String, Object> maps) {
		Project model = null;
		try {
			EnterpriseWithBLOBs e = new EnterpriseWithBLOBs();
			String orgId = UserUtils.getOrgId();
			e.setOrgId(orgId);
			List<Enterprise> eList = enterpriseServiceImpl.queryList(e);
			ApproveRoleGroup ag = new ApproveRoleGroup();
			ag.setOrgId(orgId);
			ag.setType(5);

			ag = approveRoleGroupServiceImpl.unique(ag);
			if (null == ag) {
				if (LOGGER.isInfoEnabled()) {
					LOGGER.info("法律合规部门未设置");
				}
				maps.put("approveRoleGroupMemberList", ListUtils.EMPTY_LIST);
			} else {
				ApproveRoleGroupMember approve = new ApproveRoleGroupMember();
				approve.setId(ag.getId());
				List<ApproveRoleGroupMember> aMembers = approveRoleGroupMemberServiceImpl
						.getApproveGroupEmpList(approve);
				maps.put("approveRoleGroupMemberList", aMembers);
			}

			maps.put("enterpriseList", eList);
			LOGGER.info("edit project detail param id: [{}]",JSON.toJSONString(id));
			model = projectServiceImpl.get(id);
			ProjectAttachment pAttachment = new ProjectAttachment();
			pAttachment.setProjectId(id);
			pAttachment.setType(1);
			List<ProjectAttachment> paList = projectAttachmentServiceImpl.queryList(pAttachment);
			maps.put("project", model);
			maps.put("projectAttachmentList", paList);
		} catch (Exception e) {
			LOGGER.info("query project error,msg = [{}]",e.getMessage() );
			return "common/error";
		}
		return "project/edit";
	}

	/**
	 * 更新项目信息
	 * 
	 * @param model
	 *            要更新的项目信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JsonBean update(HttpServletRequest request,
			@Valid ProjectReqBean model,
			@RequestParam(value = "fileList", required = false) List<MultipartFile> fileList,
			BindingResult errors) {
		JsonBean bean = new JsonBean();
		try {
			if (StringUtils.isBlank(model.getId())) {
				bean.setCode(0);
				bean.setMessage("id不能为空");
				LOGGER.error("id不能为空");
				return bean;
			}
			if (StringUtils.isBlank(model.getType().toString())) {
				bean.setCode(0);
				bean.setMessage("类型不能为空");
				LOGGER.error("类型不能为空");
				return bean;
			}
			if (2 == model.getType()) {
				model.setGuaranteeType(null);
				model.setGuaranteeEnterpriseId(null);
				model.setGuaranteeAssess(null);
				if (LOGGER.isInfoEnabled()) {
					LOGGER.info("类型为股权类 三个参数设为null");
				}
			} else {
				if (StringUtils.isBlank(model.getGuaranteeType().toString())) {
					bean.setCode(0);
					bean.setMessage("当前类型下担保方式不能为空");
					LOGGER.error("当前类型下担保方式不能为空");
					return bean;
				}
				Integer guarantee = model.getGuaranteeType();
				if (1 == guarantee) {
					if (StringUtils.isBlank(model.getGuaranteeEnterpriseId())) {
						bean.setCode(0);
						bean.setMessage("参数不齐");
						LOGGER.error("类型参数不齐");
						return bean;
					}
					model.setGuaranteeAssess(null);
					if (LOGGER.isInfoEnabled()) {
						LOGGER.info("保证 抵押物状况设为null");
					}
				} else {
					if (StringUtils.isAnyBlank(
							model.getGuaranteeEnterpriseId(),
							model.getGuaranteeAssess())) {
						bean.setCode(0);
						bean.setMessage("参数不齐");
						LOGGER.error("类型参数不齐");
						return bean;
					}
				}
			}
			if (StringUtils.isAnyBlank(model.getAmount().toString(),
					model.getCode(), model.getEnterpriseId(),
					model.getIntroduction(), model.getLawEmployeeId(),
					model.getName())) {
				bean.setCode(0);
				bean.setMessage("参数不齐");
				LOGGER.error("基础参数不齐");
				return bean;
			}
			bean = projectServiceImpl.updateProject(model, fileList);
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}
	
	/**
	 * 删除附件信息
	 * @param id
	 *            要删除的附件ID
	 */
	@ResponseBody
	@RequestMapping("/attachmentDelete")
	public JsonBean attachmentDelete(String id){
		JsonBean json = new JsonBean();
		if (StringUtils.isBlank(id)) {
			json.setCode(0);
			json.setMessage("id不能为空！");
			return json;
		}
		int result = projectAttachmentServiceImpl.deleteById(id);
		if (1 == result) {
			json.setCode(1);
			json.setMessage(SUCCESS);
			return json;
		} else {
			json.setCode(0);
			json.setMessage("删除项目附件失败");
			return json;
		}
	}
	

	/**
	 * 对数据进行验证
	 * 
	 * @param model
	 *            待验证的参数
	 * @param errors
	 *            验证结果
	 * @return true成功，false失败
	 */
	@ResponseBody
	@RequestMapping("/check")
	public boolean check(Project model, Integer type) {
		model.setType(null);
		if (type == null) {
			return false;
		}
		if (type == 1) { // 项目名称
			if (model.getName() == null) {
				return false;
			}
		} else if (type == 2) {//项目编号
			if (model.getCode() == null) {
				return false;
			}
		} else if (type == 3) {//修改项目名称，已经存在的不行但是自己的可以
			if (model.getName() == null) {
				return false;
			}
			Project project = projectServiceImpl.get(model.getId());
			if (model.getName().equals(project.getName())) {
				return true;
			} else {
				model.setId(null);
			}
		} else if (type == 4) {//修改项目编号，已经存在的不行但是自己的可以
			if (model.getCode() == null) {
				return false;
			}
			Project project = projectServiceImpl.get(model.getId());
			if (model.getCode().equals(project.getCode())) {
				return true;
			} else {
				model.setId(null);
			}
		}
		int result = projectServiceImpl.countBy(model);
		// 已经存在了
		if (result >= 1) {
			return false;
		}
		return true;
	}
	
	/**
	 * 上传图片组件
	 * 
	 * @param model
	 *            要更新的关于我们信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/imgUploads")
	public JsonBean imgUploads(@RequestBody MultipartFile file) {
		JsonBean bean = new JsonBean();
		try {
			if (file != null) {
				// spring mvc已经配置了，这里再次控制一下
				if (file.getSize() > (1024 * 1024 * 1024 * 2L)) { // 2M
					bean.setCode(0);
					bean.setMessage("图片大小不能大于2M！"); // 参数错误
					return bean;
				}
				String fileName = file.getOriginalFilename();
				// 正则判断图片
				if (IMAGE.matcher(fileName).matches()) {
					LOGGER.info("request file upload, filename=[{}]", file.getOriginalFilename());
					// 上传图片
					String filePath = MyFileUtils.uploadImg(file,ImgType.PROJECT);
					LOGGER.info("upload file success, filePath=[{}]", filePath);
					bean.setCode(1);
					bean.setData(filePath);
					bean.setMessage(SUCCESS);
				} else {
					// 不是图片，清空掉，不处理
					bean.setCode(0);
					bean.setMessage("上传的图片格式有问题！");
				}
			}
			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage("添加图片失败");
			LOGGER.error("save record error.", e.getMessage());
		}

		return bean;
	}
	
	/**
     * 跳转未入库初始化列表页。
     * @param model 参数
     * @return 流程List
     */
    @RequestMapping("/nonInStoreList")
    public String nonInStoreList(Flow model, Map<String, Object> maps) {
        return "project/nonInStoreList";
    }
	
    /**
     * 跳转已入库初始化列表页。
     * @param model 参数
     * @return 流程List
     */
    @RequestMapping("/inStoreList")
    public String inStoreList(Flow model, Map<String, Object> maps) {
        return "project/inStoreList";
    }
    
	/**
	 * 获得未入库项目List，Json格式。
	 * @param model 参数
	 * @return 流程List
	 */
	@ResponseBody
	@RequestMapping("/queryProject")
	public Map<String, Object> queryProject(@RequestBody Project model) {
		getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		List<ProjectResBean> list = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrgId(UserUtils.getOrgId());
			List<ApproveGroupType> agList = getApproveGroups(UserUtils.getUserId());
			Date date = model.getCreateTime();
			if (date != null) {
				model.setEndTime(new DateTime(date).minusHours(-23).minusMinutes(-59)
						.minusSeconds(-59).toDate());
				model.setStartTime(new DateTime(date).toDate());
			}
			model.setOrderBy("p.create_time desc");
			LOGGER.info("get all nonInstore project list param=[{}].", JSON.toJSONString(model));
			list = projectServiceImpl.getAllNoInProjectList(model);
			//设置项目的操作权限
			for (ProjectResBean prb : list) {
				prb.setStateType(ProjectStateUtils.get(String.valueOf(prb.getState())));
				for (ApproveGroupType agt : agList) {
					StringBuffer groupTemp = new StringBuffer();
					if(agt.getResult() != null){
						groupTemp.append(agt.getResult());
					}
					if(agt.getType() != null){
						String type = agt.getType();
						//当项目状态为录入中状态时,只有录入此项目的投资经理才能提交审批给投资主管
						if(1==prb.getState()){
							//获取当前投资经理所在投资部
							ApproveRoleGroup arg = approveRoleGroupServiceImpl.getInvestmentHead(UserUtils.getUserId());
							ApproveRoleGroupMember params = new ApproveRoleGroupMember();
							if(arg != null && StringUtils.isNotBlank(arg.getId())){
								params.setApproveRoleGroupId(arg.getId());
							}
							params.setEmployeeId(UserUtils.getUserId());
							List<ApproveRoleGroupMember> arglist = approveRoleGroupMemberServiceImpl.pagedList(params);
							//其仍然属于投资部门,并且是录入该项目的投资经理
							if(arglist.size() > 0 && UserUtils.getUserId().equals(prb.getInvestEmployeeId())){
								groupTemp.append(type); 
							}
						//当项目状态为申请立项状态时,只有录入此项目的投资部的主管才有操作权限
						}else if(2==prb.getState()){
							//获取当前项目录入的投资经理所在的投资部
							ApproveRoleGroup arg = approveRoleGroupServiceImpl.getInvestmentHead(prb.getInvestEmployeeId());
							if(arg != null && UserUtils.getUserId().equals(arg.getEmployeeId())){
								groupTemp.append(type); 
							}
						//当项目状态是立项风控审核时,需要判断是否是当前项目的风控经理
						}else if(3==prb.getState()){
							//获取当前项目录入的风控经理所在的法律合规部
							ApproveRoleGroup arg = approveRoleGroupServiceImpl.getLawComplieHead(prb.getLawEmployeeId());
							//法律合规部负责人和新增项目选择的风控经理才有操作权限
							if((arg!= null && arg.getEmployeeId().equals(UserUtils.getUserId())) ||prb.getLawEmployeeId().equals(UserUtils.getUserId())){
								groupTemp.append(type); 
							}	
						}
						//当其是尽调小组成员时,需要判断是否是当前项目的尽调小组成员
						else if(4==prb.getState()){
							if(prb.getId().equals(agt.getProjectId())){
								groupTemp.append(type); 
							}	
						}else{
							groupTemp.append(type); 
						}
					}
					if(String.valueOf(prb.getState()) != null){
						groupTemp.append(String.valueOf(prb.getState()));
					}
					if(!StringUtils.isBlank(groupTemp.toString())){
						//当前操作权限未设置时才添加操作权限
						if(prb.getOperter() == null){
							//判断项目当前流程中该员工是否在第5/7步骤已经做过个人表决
							if((prb.getState() == 5 || prb.getState() == 7) && ("3".equals(agt.getType()) || "4".equals(agt.getType()))){
								if( isPersonalDecision(UserUtils.getUserId(),prb)){
									groupTemp.append("o");
								}
							}
							prb.setOperter(OperaterUtils.get(groupTemp.toString()));	
						}
					}
				}
			}
			LOGGER.info("set all nonInstore project list authority complete");
			// 统计的时候，不需要分页
			model.setStart(null);
			int totalRecord = projectServiceImpl.getAllNoInProjectList(model).size();
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("queryProject authority list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 获得已入库项目List，Json格式。
	 * @param model 参数
	 * @return 流程List
	 */
	@ResponseBody
	@RequestMapping("/queryStoreProject")
	public Map<String, Object> queryStoreProject(@RequestBody Project model) {
		List<ProjectResBean> list = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrgId(UserUtils.getOrgId());
			Date date = model.getCreateTime();
			if (date != null) {
				model.setEndTime(new DateTime(date).minusHours(-23).minusMinutes(-59)
						.minusSeconds(-59).toDate());
				model.setStartTime(new DateTime(date).toDate());
			}
			model.setOrderBy("p.create_time desc");
			list = projectServiceImpl.getAllInStoreProjectList(model);
			//设置项目状态
			for (ProjectResBean prb : list) {
				prb.setStateType(ProjectStateUtils.get(String.valueOf(prb.getState())));
			}	
			// 统计的时候，不需要分页
			model.setStart(null);
			int totalRecord = projectServiceImpl.getAllInStoreProjectList(model).size();
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("queryStoreProject list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 获取该员工所在的审批团队
	 */
	public List<ApproveGroupType> getApproveGroups(String employeeId){
		List<ApproveGroupType> agList = new ArrayList<ApproveGroupType>();
		try {
			ApproveRoleGroupMember argm = new ApproveRoleGroupMember();
			argm.setEmployeeId(employeeId);
			//获取员工的所有审批团队关系列表
			LOGGER.info("getApproveGroups list param=[{}].", JSON.toJSONString(argm));
			List<ApproveRoleGroupMember> argmList = approveRoleGroupMemberServiceImpl.pagedList(argm);

			for (ApproveRoleGroupMember approve : argmList) {
				ApproveGroupType agt = new ApproveGroupType();
				ApproveRoleGroup arg = approveRoleGroupServiceImpl.get(approve.getApproveRoleGroupId());
				agt.setType(String.valueOf(arg.getType()));
				if(employeeId.equals(arg.getEmployeeId())){
					agt.setResult("t");
				}
				if(StringUtils.isNotBlank(arg.getProjectId())){
					agt.setProjectId(arg.getProjectId());
				}
				agList.add(agt);
			}	
		} catch (Exception e) {
			LOGGER.error("getApproveGroups list error, errorMsg=[{}].", e.getMessage());
		}
		return agList;
	}
	
	/**
	 * 判断项目当前流程中该员工是否在当前步骤已经做过个人表决
	 */
	public boolean isPersonalDecision(String empId,ProjectResBean model){
		boolean flag = false;
		try {
			FlowLog fl = new FlowLog();
			fl.setEmployeeId(empId);
			fl.setEventId(model.getId());
			fl.setIsCurrent(true);
			if(model.getState()==5){
				fl.setStepName("初审委员会成员审批");
			}else if(model.getState()==7){
				fl.setStepName("决策委员会成员审批");
			}
			if(flowLogServiceImpl.pagedList(fl).size() == 1){
				flag = true;
			}
		} catch (Exception e) {
			LOGGER.error("isPersonalDecision  error, errorMsg=[{}].", e.getMessage());
		}
		return flag;
	}
	
	/**
	 * 获取项目的进展处理意见
	 */
	@ResponseBody
	@RequestMapping("/projectprogress")
	public Map<String, Object> projectprogress(@RequestBody Project model) {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrgId(UserUtils.getOrgId());
			FlowLog fl = new FlowLog();
			fl.setEventId(model.getId());
			List<FlowLog> flList = flowLogServiceImpl.myPagedList(fl);
			// 统计的时候，不需要分页
			model.setStart(null);
			int totalRecord = flowLogServiceImpl.countBy(fl);
			result.put("aaData", flList); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error(" query projectprogress list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	
	/**
	 * 获取项目的尽调文件和合同文件
	 */
	@ResponseBody
	@RequestMapping("/projectReport")
	public Map<String, Object> projectReport(@RequestBody ProjectAttachment model) {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
			model.setOrgId(UserUtils.getOrgId());
			List<ProjectAttachment> flList = projectAttachmentServiceImpl.getReportList(model);
			// 统计的时候，不需要分页
			model.setStart(null);
			int totalRecord = projectAttachmentServiceImpl.countBy(model);
			result.put("aaData", flList); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("query Project file list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 获取项目的评级信息
	 */
	@ResponseBody
	@RequestMapping("/projectGrade")
	public Map<String, Object> projectGrade(@RequestBody ProjectGrade model) {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
			List<ProjectGrade> flList = projectGradeServiceImpl.getGradeList(model);
			// 统计的时候，不需要分页
			model.setStart(null);
			int totalRecord = projectGradeServiceImpl.countBy(model);
			result.put("aaData", flList); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("query project Grade list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 获取项目的配资信息
	 */
	@ResponseBody
	@RequestMapping("/projectAsset")
	public Map<String, Object> projectAsset(@RequestBody ProjectGrade model) {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			//根据项目id获取资产配资信息
			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
			AssetAllocationDetail aad = new AssetAllocationDetail();
			aad.setProjectId(model.getProjectId());
			List<AssetAllocationDetail> flList = assetAllocationDetailServiceImpl.getAssetList(aad);
			//统计的时候，不需要分页
			model.setStart(null);
			int totalRecord = assetAllocationDetailServiceImpl.countByAssetList(aad);
			result.put("aaData", flList); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("query projectAsset list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	/** 
	* @Title: enterpriseAdd 
	* @Description: 再没了就不玩了 
	* @Time:2016年4月27日 下午3:21:23
	* @return 
	* String    返回类型 
	*/
	@RequestMapping("/enterpriseAdd")
	public String enterpriseAdd() {
		return "project/enterpriseAdd";
	}
	
	
}
